/**
 * 
 */
package io.dora.registry.zk;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ZK工具类
 *
 * @author zhaohongbo
 *
 */
public class ZkUtils {

	private static Logger LOGGER = LoggerFactory.getLogger(ZkUtils.class);
	
	public static final String separator = "/";
	public static final String spliter = ",";
	
	/**
	 * 级联创建Zk 路径
	 * 
	 * @param zk Zk client
	 * @param path eg:/ab/cd/ef/g
	 */
	public static boolean createNode(ZooKeeper zk, String path) {
		boolean flag = true;
		if (!path.startsWith(separator)) {
			path = separator + path;
		}
		
		try {
			String nodeName = "";
			String[] pathArray = StringUtils.split(path, separator);
			for (int i = 0, len = pathArray.length; i < len; i++) {
				String node = pathArray[i];
				if (StringUtils.isBlank(node)) {
					continue;
				}
				nodeName = nodeName + separator + node;
				Stat stat = zk.exists(nodeName, false);
				if (stat == null) {
					zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
				}
			}
		} catch (Exception e) {
			LOGGER.error("{}", e);
			flag = false;
		}
		
		return flag;
	}
	
	
	/**
	 * 给Zk节点添加或更新数据
	 * 
	 * @param zk
	 * @param path
	 * @param data
	 * @param append true表示可追加
	 */
	public static void addOrUpdateNodeData(ZooKeeper zk, String path, String data, boolean append) {
		if (!path.startsWith(separator)) {
			path = separator + path;
		}
		try {
			if (append) {
				String existsData = getNodeData(zk, path);
				if (StringUtils.isNotBlank(existsData)) {
					StringBuffer dataBuffer = new StringBuffer(existsData);
					dataBuffer.append(spliter).append(data);
					data = dataBuffer.toString();
					String[] arrays = StringUtils.split(data, spliter);
					Set<String> dataSet = new HashSet<String>(Arrays.asList(arrays));
					data = StringUtils.join(dataSet, spliter);
				}
			}
			LOGGER.info("path {} data  {}", path, data);
			Stat stat = zk.exists(path, false);
			if (stat != null) {
				zk.setData(path, data.getBytes(), -1);
			}
		} catch (Exception e) {
			LOGGER.error("{}", e);
		}
	}
	
	/**
	 * 获取Zk 节点的数据
	 * 
	 * @param zk
	 * @param path
	 * @return
	 */
	public static String getNodeData(ZooKeeper zk, String path) {
		if (!path.startsWith(separator)) {
			path = separator + path;
		}
		String data = "";
		try {
			Stat stat = zk.exists(path, false);
			if (stat != null) {
				byte[] bdata = zk.getData(path, false, null);
				if (bdata != null) {
					data = new String(bdata);
				}
			}
		} catch (Exception e) {
			LOGGER.error("{}", e);
		}
		return data;
	}
	
	public static void main(String[] args) {
		createNode(null, "a/bc/c//");
	}
}
